package com.net.xpay.core.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundBatchDetailQueryResponse;
import com.net.common.util.SerializationUtil;
import com.net.xpay.alipay.PoseidonAlipayClient;
import com.net.xpay.core.domain.AlipayUser;
import com.net.xpay.core.enums.PayTransBatchStatus;
import com.net.xpay.core.manager.AlipayUserManager;
import com.net.xpay.core.service.AlipayFundBatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 2020/5/10 15:09

 */
@Slf4j
@Service
public class AlipayFundBatchServiceImpl implements AlipayFundBatchService {

    @Autowired
    private AlipayUserManager alipayUserManager;

    @Autowired
    private PoseidonAlipayClient xpayAlipayClient;

    @Override
    public AlipayFundBatchDetailQueryResponse allDetailQuery(Long alipayUserId, String outBatchNo) throws AlipayApiException {
        AlipayFundBatchDetailQueryResponse toReturnResponse = detailQuery(alipayUserId, outBatchNo, 1L);
        if (!toReturnResponse.isSuccess() || toReturnResponse.getBatchStatus() == null) {
            log.warn("allDetailQuery error|resp={}|alipayUserId={}|outBatchNo={}", SerializationUtil.obj2String(toReturnResponse), alipayUserId, outBatchNo);
            return toReturnResponse;
        }
         String batchStatus = toReturnResponse.getBatchStatus();
        // INIT 接受 | WAIT_PAY 等待付款 不处理 DEALING 不处理
        if (PayTransBatchStatus.INIT.getValue().equals(batchStatus) || PayTransBatchStatus.WAIT_PAY.getValue().equals(batchStatus)
                || PayTransBatchStatus.DEALING.getValue().equals(batchStatus)) {
            return toReturnResponse;
        }
        Long totalPageCount = toReturnResponse.getTotalPageCount();
        Long pageNum = 1L;
        while (pageNum <= totalPageCount) {
            pageNum++;
            if (pageNum <= totalPageCount) {
                AlipayFundBatchDetailQueryResponse response = detailQuery(alipayUserId, outBatchNo, pageNum);
                if (!response.isSuccess() || response.getBatchStatus() == null) {
                    log.warn("page allDetailQuery error|resp={}|alipayUserId={}|outBatchNo={}|pageNum={}", SerializationUtil.obj2String(toReturnResponse), alipayUserId, outBatchNo, pageNum);
                    return toReturnResponse;
                }
                toReturnResponse.getAccDetailList().addAll(response.getAccDetailList());
            }
        }
        return toReturnResponse;
    }

    private AlipayFundBatchDetailQueryResponse detailQuery(long alipayUserId, String outBatchId, long pageNum) throws AlipayApiException {
        AlipayUser alipayUser = alipayUserManager.getById(alipayUserId);
        return xpayAlipayClient.alipayFundBatchDetailQuery(alipayUser.getAuthToken(), outBatchId, pageNum);
    }

}
